# -*- coding:utf-8 -*-
"""
权限管理
"""
import copy
import logging

from LibrarySystem.services.interface.role_service_interface import RoleServiceInterface
from LibrarySystem.repositories.mongodb.models.user_models import User

module_logger = logging.getLogger("logger")


class RoleManager(RoleServiceInterface):
    """
    @ClassName：RoleManager
    @Description： 角色管理器，本项目只有一个实例
    负责保存 当前登录用户，当前权限，检查权限
    @Author：锦沐Python
    """
    # 权限编号，仅作展示记录
    _AUTH_NO = {
        "图书录入": 0,
        "图书更新": 1,
        "图书查询": 2,
        "图书统计": 3,
        "用户信息": 4,
        "图书分类统计": 31,
        "图书出版年份数量统计": 32,
        "图书总体借阅情况统计": 33,
        "关键词借阅统计": 34,
        "关键词匹配名称统计": 35,
        "用户借阅分类情况": 36,
        "用户借阅历史": 37,
    }

    # 角色列表
    _ROLES = [
        {"role": "admin", "position": "系统管理员", "permissions": [0, 1, 2, 3, 4, 31, 32, 33, 34, 35]},
        {"role": "user", "position": "普通操作员", "permissions": [2, 3, 4, 34, 35, 36, 37]}
        ]

    def __init__(self):
        # 当前角色
        self._current_role = None
        # 当前权限
        self._current_permissions = None
        # 当前登录用户
        self._login_user = None

    def get_current_role_permissions(self):
        """
        获取登录用户权限
        @return:
        """
        if self._current_role is None or self._current_permissions is None:
            module_logger.error("用户未登录，无法操作")
            return (False, "用户未登录，无法操作")
        return (True, self._current_permissions)

    def set_current_role(self, user: User):
        """
        配置用户权限
        @param user:
        @return:
        """
        self._login_user = copy.deepcopy(user)

        for roles in self._ROLES:
            if self._login_user.role == roles["role"]:
                self._current_role = roles["role"]
                self._current_permissions = roles["permissions"]

                module_logger.info(f"当前为 {self._login_user.role } 权限")
                return (True, f"当前为 {self._login_user.role } 权限")

        module_logger.error(f"不存在 {self._login_user.role } 权限")
        return (False, f"不存在 {self._login_user.role } 权限")
    
    def check_permissions(self, permission):
        """
        检测权限是否存在用户权限
        @param permission:
        @return:
               """
        if self._current_permissions is None:
            return (False, "未登录")

        flag = set(permission).issubset(self._current_permissions)
        if flag:
            return (True, "检查通过")
        else:
            return (False, "检查未通过")

    def get_current_user(self):
        """
        获取登录用户信息
        @return:
        """
        if self._login_user is None:
            return (False, "用户未登录")
        return (True, self._login_user)

    def get_current_role(self):
        """
        获取当前角色
        @return:
        """
        if self._current_role is None:
            return (False, "用户未登录")
        return (True, self._current_role)

    def get_roles(self):
        """
        获取当前角色列表
        @return:
        """
        roles = set()
        for role in self._ROLES:
            roles.add(role["role"])
        if roles:
            return (True, roles)
        return (False, "")

#
# from functools import wraps
# # 权限管理装饰器
# def requires_auth(role=None):  # 装饰器接受一个名为role的参数，默认为"user"
#     if role is None:
#         role = ["user", ]
#     def decorator(target_fun):
#         @wraps(target_fun)
#         def decorated(*args, **kwargs):
#             if  all(elem in role for elem in global_config.get_role()):
#                 module_logger.info(f"{role}验证通过")
#                 # 如果角色匹配，执行原函数
#                 return target_fun(*args, **kwargs)
#             else:
#                 module_logger.info(f"{global_config.get_role()}验证失败, 当前权限为{role}")
#                 # 如果角色不匹配，打印验证失败并返回False
#                 return (False, "验证失败，无权限访问")
#         return decorated
#
#     return decorator